package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bwie.until.R;
import com.ruoyi.pojo.Coupon;
import com.ruoyi.pojo.Driver;
import com.ruoyi.pojo.Order;
import com.ruoyi.pojo.Passenger;
import com.ruoyi.service.CouponService;
import com.ruoyi.service.DriverService;
import com.ruoyi.service.OrderService;
import com.ruoyi.service.PassengerService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: liufei
 * @Desc:
 * @create: 2024-11-07 10:35
 **/
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private PassengerService passengerService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/SuccessOrder/{orderId}")
    public R SuccessOrder(@PathVariable String orderId, @RequestHeader String token){
        // 修改订单状态
        LambdaUpdateWrapper<Order> wrapper1 = new LambdaUpdateWrapper<>();
        wrapper1.eq(Order::getOrderId, orderId).set(Order::getOrderStatus, "订单已完成").set(Order::getEndTime, new Date());
        orderService.update(wrapper1);

        // 修改司机余额
        LambdaQueryWrapper<Order> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Order::getOrderId, orderId);
        Order one = orderService.getOne(wrapper2);

        Driver driver = driverService.getById(one.getDriverId());
        Double price = driver.getPrice();

        LambdaUpdateWrapper<Driver> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Driver::getId, one.getDriverId()).set(Driver::getPrice, price+one.getPrice());
        driverService.update(wrapper);
        return R.ok();
    }


    @PostMapping("/FindMy")
    public R FindMy(@RequestHeader String token){
        // 解析token
        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();

        Integer userId = claims.get("userId", Integer.class);

        // 根据用户id查询司机信息
        QueryWrapper<Driver> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(Driver::getId, userId);

        Driver driver = driverService.getOne(wrapper);

        return R.ok(driver);
    }

    @PostMapping("/cancalOrder/{orderId}")
    public R backOrder(@PathVariable String orderId){

        // 根据订单id查询订单信息
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderId, orderId);
        Order one = orderService.getOne(wrapper);
        Double onePrice = one.getPrice();
//        则根据设置5分钟，30分钟，60分钟分别扣除相应金额，退还乘客剩余金额
        long startTime = one.getStartTime().getTime();
        long nowTime = new Date().getTime();
        if(nowTime-startTime<=5*60*1000){

            LambdaQueryWrapper<Driver> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Driver::getId, one.getUserId());
            Driver driver = driverService.getOne(wrapper1);
            Double TwoPrice = onePrice - 5;

            LambdaUpdateWrapper<Driver> wrapper3 = new LambdaUpdateWrapper<>();
            wrapper3.eq(Driver::getId, one.getUserId()).set(Driver::getPrice, driver.getPrice()+TwoPrice);
            driverService.update(wrapper3);
        }else if(nowTime-startTime<=30*60*1000){
            LambdaQueryWrapper<Driver> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Driver::getId, one.getUserId());
            Driver driver = driverService.getOne(wrapper1);
            Double TwoPrice = onePrice - 5;

            LambdaUpdateWrapper<Driver> wrapper3 = new LambdaUpdateWrapper<>();
            wrapper3.eq(Driver::getId, one.getUserId()).set(Driver::getPrice, driver.getPrice()+TwoPrice);
            driverService.update(wrapper3);
        }else{
            LambdaQueryWrapper<Driver> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Driver::getId, one.getUserId());
            Driver driver = driverService.getOne(wrapper1);
            Double TwoPrice = onePrice - 5;

            LambdaUpdateWrapper<Driver> wrapper3 = new LambdaUpdateWrapper<>();
            wrapper3.eq(Driver::getId, one.getUserId()).set(Driver::getPrice, driver.getPrice()+TwoPrice);
            driverService.update(wrapper3);
        }

        // 修改订单状态
        LambdaUpdateWrapper<Order> wrapper1 = new LambdaUpdateWrapper<>();
        wrapper1.eq(Order::getOrderId, orderId).set(Order::getOrderStatus, "取消订单");
        orderService.update(wrapper1);

        return R.ok();
    }

    /**
     * 订单详情/接单
     * @param id
     * @return
     */
    @PostMapping("/FindOrder/{id}")
    public R FindOrder(@PathVariable String id,@RequestHeader String token){

        // 根据订单id查询订单信息
        Order order = orderService.getById(id);

        String orderId = order.getOrderId();

        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();

        Integer userId = claims.get("userId", Integer.class);

        // 判断订单状态，如果状态为待接单，则修改订单状态，并发送消息给司机
        if(order.getOrderStatus().equals("待接单")){
            LambdaUpdateWrapper<Order> wrapper1 = new LambdaUpdateWrapper<>();
            wrapper1.eq(Order::getId, id).set(Order::getOrderStatus, "已接单").set(Order::getDriverId, userId);
            orderService.update(wrapper1);

            stringRedisTemplate.opsForValue().set("orderId:"+orderId,orderId,10, TimeUnit.MINUTES);
            rabbitTemplate.convertAndSend("javaExchange","java",orderId);
            System.out.println("订单发送时间:"+new Date());
        }

        // 根据用户id查询乘客信息
        LambdaQueryWrapper<Passenger> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Passenger::getUserId, order.getUserId());
        Passenger passenger = passengerService.getOne(wrapper);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("order",order);
        hashMap.put("passenger",passenger);
        return R.ok(hashMap);
    }



    /**
     * 显示优惠券
     * @param token
     * @return
     */
    @GetMapping("/ShowCoupon")
    public R ShowCoupon(@RequestHeader String token){

        // 解析token
        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();

        Integer userId = claims.get("userId", Integer.class);

        // 根据用户id查询优惠券信息
        QueryWrapper<Coupon> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(Coupon::getUserId, userId);

        List<Coupon> couponList = couponService.list(wrapper);

        return R.ok(couponList);
    }

    /**
     * 订单列表
     * @param token
     * @return
     */
    @GetMapping("/OrderList")
    public R OrderList(@RequestHeader String token){

        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();

        String role = claims.get("role", String.class);
        Integer userId = claims.get("userId", Integer.class);

        // 根据用户角色查询订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        if(role.equals("0")){

            wrapper.lambda().eq(Order::getUserId, userId);

        }
        List<Order> orderList = orderService.list(wrapper);


        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("orderList",orderList);
        hashMap.put("role",role);
        return R.ok(hashMap);
    }

    /**
     * 添加订单
     * (4)每个订单除了ID外，还有一个编号：规则为，18位：4位年+2位月+2位日+10位序号：实现方案：前8位通过当前时间获取。后10位通过Redis的INCR 命令实现。
     * @param order
     * @return
     */
    @PostMapping("/addOrder")
    @Transactional
    public R addOrder(@RequestBody Order order,@RequestHeader String token){

        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();

        Integer userId = claims.get("userId", Integer.class);

//        (4)每个订单除了ID外，还有一个编号：规则为，18位：4位年+2位月+2位日+10位序号：实现方案：前8位通过当前时间获取。后10位通过Redis的INCR 命令实现。
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String time = format.format(new Date());
        System.out.println("time:"+time);
        Jedis jedis = new Jedis("localhost");
        String s = jedis.get("orderId:");
        System.out.println("s:"+s);
        Long incred = jedis.incr("orderId:");
        //(4)前8位通过当前时间获取。后10位通过Redis的INCR 命令实现。
        String orderId = time + String.format("%010d", incred);
        System.out.println("order:"+orderId);

        // 添加订单
        order.setOrderId(orderId);
        order.setOrderStatus("待接单");
        order.setUserId(userId);
        orderService.save(order);

        // 添加优惠券
        Coupon coupon = new Coupon();
        coupon.setName("满五十减十元");
        coupon.setMoney("10");
        coupon.setStartTime(new Date());
        coupon.setValidTime("五天");
        coupon.setUserId(userId);
        couponService.save(coupon);
        return R.ok();
    }


}
